const express = require('express')
const router = express.Router()
const moment = require("moment")
const fs = require("fs")
const multer = require("multer")
const path = require("path")
const userDb = require('../db/user-db')
const {logI} = require('../log.js')
const fsPromises = require('fs/promises');
const {retError, retSuccess} = require('../utils/ret')
const checkToken = require('../utils/checkToken')
const checkDeviceNo = require('../utils/checkDeviceNo')
const checkType = require('../utils/checkType')

const storage = multer.diskStorage({
    //文件存储路径
    destination: function (req, file, cb) {
        const tempsDir = fs.existsSync( path.join(__dirname, "/../public/uploads/temps"));
        logI('A-S', "temps path", 'imageUpload', `${JSON.stringify(path.join(__dirname, "/../public/uploads/temps"))}`, 'null')
        if(!tempsDir){
            if(!fs.existsSync( path.join(__dirname, "/../public"))){
                fs.mkdirSync( path.join(__dirname, "/../public"));
                logI('A-S', "create public", 'imageUpload', ``, 'null')
            }
            if(!fs.existsSync( path.join(__dirname, "/../public/uploads"))){
                fs.mkdirSync( path.join(__dirname, "/../public/uploads"));
                logI('A-S', "create uploads", 'imageUpload', ``, 'null')
            }
            if(!fs.existsSync( path.join(__dirname, "/../public/uploads/temps"))){
                fs.mkdirSync( path.join(__dirname, "/../public/uploads/temps"));
                logI('A-S', "create temps", 'imageUpload', ``, 'null')
            }
        }else {
            fsPromises.stat("/../public/uploads/temps")
                .then((stats) => {logI('A-S1', "create temps", 'imageUpload', `${JSON.stringify(stats.mode)}`, 'null')})
                .catch((err) => {logI('A-S2', "create temps", 'imageUpload', `${JSON.stringify(err)}`, 'null')})
        }
        cb(null, path.join(__dirname, "/../public/uploads/temps"));
        //cb(null, path.join("/public/uploads/temps"));
    }
});
let upload = multer({storage : storage });

router.post('/', upload.single('file'), async function (req, res, next) {
    //console.log(req)
    let {body: {maddr,token, meshUUID,deviceNo,version,buildingUUID}} = req
    logI('A-S', maddr, 'imageUpload', `${JSON.stringify(req.body)}`, 'null')
    const error = checkType.fileUpload(req.body)
    if(error){
        retError("imageUpload",maddr, 10001,  error.details[0].message, res);
    }else{
        if(req.file!==undefined){
            const imageName = req.file.originalname;
            const destDir = "images/"+moment().format("YYYYMMDD");
            const sourceImage = req.file.path;
            let msg = {};
            msg = await checkToken(token,maddr);
            if(msg.code === 0){
                const deviceInfo={
                    'maddr':maddr,
                    'deviceNo':deviceNo
                }
                let device={};
                device = await checkDeviceNo(deviceInfo);
                if(device.code === 0){
                    let versionData = {};
                    versionData = await userDb.getVersion(buildingUUID,meshUUID);
                    if(versionData.version){
                        if(parseInt(versionData.version) === parseInt(version)){
                            let imagesDir = fs.existsSync( path.join(__dirname, "/../public/uploads/images"));
                            if(!imagesDir){
                                fs.mkdirSync( path.join(__dirname, "/../public/uploads/images"));
                            }
                            const destPath = path.join(__dirname.replace("router", "public"), "uploads", destDir, imageName);
                            const dest_Dir = path.join(__dirname.replace("router", "public"), "uploads", destDir);
                            let imageUrl = destPath.substr(destPath.indexOf("uploads"));
                            imageUrl = "/"+imageUrl.replace(/\\/g, "/");
                            fs.access(dest_Dir, function (err) {
                                if(err == null){
                                    uploadImage(maddr,meshUUID,imageUrl,sourceImage,destPath,res,function (code){
                                        const msg={
                                            "url":"https://" + process.env.DOMAIN +imageUrl
                                        }
                                        retSuccess("imageUpload", maddr,0, msg, res);
                                    });
                                }else if(err.code == "ENOENT"){
                                    console.log(dest_Dir)
                                    fs.mkdir(dest_Dir, 777, function (err) {
                                        if (err) {
                                            retError("imageUpload", maddr,10003, "imageUpload failed", res);
                                        } else {
                                            uploadImage(maddr,meshUUID,imageUrl,sourceImage,destPath,res,function (code){
                                                const msg={
                                                    "url":"https://" + process.env.DOMAIN +imageUrl
                                                }
                                                retSuccess("imageUpload", maddr,0, msg, res);
                                            });
                                        }
                                    })
                                }
                            });
                        }else{
                            retError("imageUpload", maddr,10020, "The version number is incorrect, the current version number is "+`${versionData.version}`, res);
                        }
                    }else{
                        retError("imageUpload", maddr,10019, "mesh does not exist", res);
                    }
                }else{
                    retError("imageUpload", maddr,device.code, device.body, res);
                }
            }else{
                retError("imageUpload", maddr,msg.code, msg.body, res);
            }
        }else{
            retError("imageUpload",maddr, 10001,  "image is require", res);
        }

    }

});

function uploadImage(maddr,meshUUID,imageUrl,sourceImage,destPath,res,cb){
    fs.rename(sourceImage, destPath, function (err) {
        cb(0);
        logI('A-S', maddr, 'imageUpload', `${JSON.stringify({ctl_status: '0'})}`, 'null')
        const updateTime = moment().format('YYYY-MM-DD HH:mm:ss');
        userDb.updateImage(imageUrl,updateTime,meshUUID)
            .then((result) => {
                const time = new Date().getTime();
                const date = moment().format('YYYY-MM-DD');
                userDb.insertLogImage(maddr,imageUrl,meshUUID,time,date)
                    .then((result) => {
                    })
                    .catch((err) => {
                        logI('A-S', maddr, 'imageUpload', `${JSON.stringify(err)}`, 'null')
                    })
            })
            .catch((err) => {
                logI('A-S', maddr, 'imageUpload', `${JSON.stringify(err)}`, 'null')
            })

    });
}

module.exports = router
